<?php
class PHZ_Scoring
{
    /**
     * 本类为胡牌后；计算分数用的类；并不参与胡牌结束后的前端处理
     * @param $room_info    房间ID信息
     * @param $huxi         胡息数
     * @param $hupai_uid    胡牌人的ID
     * @param $pao_uid      放炮人的ID（如果mode为0的情况下，就会存在放炮人）
     * @param $card_number  牌号
     * @param $mode         胡牌方式（0，1，2,3）。放炮，公炮，2 自摸 ， 3 黄庄
     * @param $db_connect   数据链接标识
     */
    public static function __game_Single_END( $room_info , $huxi , $hupai_uid , $pao_uid = 0 ,  $card_number , $mode , $db_connect ){
        $room_id   = $room_info['room_id'];
        $card_info = $db_connect->select('*')->from('tt_room_card')->where("jid = '". $room_info['room_js'] ."' and rid= '". $room_id ."' ")->query();//取出所有该房间的牌面信息
        //胡牌用户的牌面数组记录
        $hupai_userCardInfo = null;
        //计算胡牌用户是否为天地胡(分别为没有出过牌且区分庄还是不是庄的情况即可)
        $is_tianDI = 0;
        foreach ( $card_info as $key => $value ){
            if( $value['uid'] == $hupai_uid ){
                if( trim($value['put_log']) == "" && $value['zid'] == $hupai_uid ){
                    $is_tianDI = 1;break;//天胡
                }
                if( trim($value['put_log']) == "" && $value['zid'] != $hupai_uid ){
                    $is_tianDI = 2;break;//地胡
                }
                //设置胡牌人的牌面信息
                $hupai_userCardInfo = $value;
            }
        }
        //流局情况下，不需要进行番薯跟分的计算
        if( $mode == 3 ){
            $mt_plus  = array( 'mode_type' => 0 , 'plus' => 0 );
            $pl_score = array( 'player_1' => 0 ,'player_2' => 0 ,'player_3' => 0 ,'player_4' => 0 , 'xing' => array() );
            $pl_score['xing']['xing_card']  = 0;$pl_score['xing']['xing_count'] = 0;//流局，醒为0
        }else {
            $mt_plus  = self::__get_ModeType_AND_PLUS($room_info, $card_info, $hupai_uid, $card_number, $mode , $is_tianDI );
            $pl_score = self::__Calculation_score($room_info, $huxi, $hupai_uid, $pao_uid, $mt_plus , $hupai_userCardInfo , $card_number , $db_connect );
        }
        //添加本局计分信息
        $data = array();
        $data['room_id']        = $room_info['room_id'];
        $data['room_js']        = $room_info['room_js'];
        $data['mode']           = $mode;
        $data['mode_type']      = $mt_plus['mode_type'];
        $data['hu_xi']          = $huxi;
        $data['plus']           = $mt_plus['plus'];
        $data['player_1']       = $room_info['room_player_1'];
        $data['player_2']       = $room_info['room_player_2'];
        $data['player_3']       = $room_info['room_player_3'];
        $data['win_uid']        = $hupai_uid;
        $data['pao_uid']        = $pao_uid;
        $data['player_1_score'] = $pl_score['player_1'];
        $data['player_2_score'] = $pl_score['player_2'];
        $data['player_3_score'] = $pl_score['player_3'];
        $data['add_time']       = date('Y-m-d H:i:s');
        $data['card_number']    = $card_number;
        $data['xing_card']      = (int)$pl_score['xing']['xing_card'];
        $data['xing_count']     = (int)$pl_score['xing']['xing_count'];
        $db_connect->insert('tt_room_scoring')->cols( $data )->query();
        $data['room_maxjs']     = $room_info['room_zjs'];//插入一个总局数给前端调用
        //更新所有人的本房间计分信息
        $cols = array();
        $cols['player_1_score'] = $room_info['player_1_score'] + $pl_score['player_1'];
        $cols['player_2_score'] = $room_info['player_2_score'] + $pl_score['player_2'];
        $cols['player_3_score'] = $room_info['player_3_score'] + $pl_score['player_3'];
        for ( $i = 1 ; $i <= 3 ; $i++ ){//去除所有人的胡，碰，吃状态
            $cols['p'.$i.'_is_hu'] = 0;$cols['p'.$i.'_is_peng'] = 0;$cols['p'.$i.'_is_chi'] = 0;
            $cols['p' . $i . '_start' ] = 0;//所有人都为未准备状态
        }
        $cols['banker']      = $mode == 3 ? $room_info['banker'] : $hupai_uid;//非流局，赢家为庄；流局；继续上个庄为庄
        $cols['scor_status'] = 1;//当前房间状态处于结算状态
        //如果当前局数已经大于等于总局数，则下发游戏结束通知；否则下发下一局准备通知
        $game_end = false;
        if( $room_info['room_js'] >= $room_info['room_zjs'] ){
            $game_end = true;
            $cols['room_status']   = 2;//如果已经结束，状态修改为2
            $cols['room_end_time'] = date('Y-m-d H:i:s');//游戏结束时间
        }
        //清除一些rec数据
        $cols['this_timer'] = 0;
        $cols['tp_uid']     = 0;$cols['tp_card'] = 0;
        $cols['tm_uid']     = 0;$cols['tm_card'] = 0;
        $cols['this_put']   = 0;
        //执行修改
        $db_connect->update('tt_room')->cols( $cols )->where('room_id=' . $room_id)->query();
        //给所有人发送胡牌消息(并附加游戏是否已全局结束的通知)
        $temp = array();
        $temp['pl']   = 88;//88为胡牌
        $temp['hu']   = $data;//胡牌信息
        $temp['cols'] = $cols;//总积分信息
        foreach ( $card_info as $key => $value ){//将手牌跟下牌重新组合成end_pai，供前端使用
            $temp_xp = str_replace("_",",", $value['xp'] );
            if( $value['uid'] == $hupai_uid ){
                $san_lian = $card_number."_".$card_number."_".$card_number;//（更新：最后再加入一个胡的牌*胡牌人,1.4连或3连不加）
                $si_lian  = $card_number."_".$card_number."_".$card_number."_".$card_number;
                if( strstr( $value['xp'] , $san_lian ) != false || strstr( $value['xp'] , $si_lian ) != false ){
                    $end_pai = $temp_xp . $value['sp'];
                }else{
                    $end_pai = $temp_xp . $value['sp'] . "," . $card_number;
                }
            }else{
                $end_pai = $temp_xp . $value['sp'];
            }
            if( $value['uid'] == $hupai_uid ) {
                $card_info[$key]['end_pai'] = PHZ_LiPai::__lipai($end_pai, true, $room_info, $card_number, $hupai_userCardInfo);
            }else{
                $card_info[$key]['end_pai'] = PHZ_LiPai::__lipai($end_pai, true, $room_info);
            }
        }
        $temp['card'] = $card_info;//牌面信息
        $temp['ge']   = $game_end;//本房间是否结束？
        if( $game_end == true ){
            $temp['js'] = PM_f::__index( $room_id , $db_connect );
        }
        PHZ_Log::__send_user_log( $room_info , $hupai_uid , $temp , $db_connect );
        //返回true
        return true;
    }

    /**
     * 获取大胡的各种判断方式以及返回(这里也需要根据房间是否设置了该些玩法来计算)
     * @param $room_info   房间信息
     * @param $card_info   牌面信息
     * @param $hupai_uid   胡牌人ID
     * @param $is_tianDI   是否天地胡
     * @param $card_number
     * @param $mode
     * 重要备注：
     * 1.大红 2 小红 3 一点红 4 黑胡 5 大字胡 6 小字胡 7 天胡 8 地胡 9 碰碰胡
     *
     * 前端开房代号：1 2分 2 一五十 3 红黑胡 4 天地大小字胡 5 一点红 6 碰碰胡 7 翻醒 8 随醒
     */
    public static function __get_ModeType_AND_PLUS( $room_info , $card_info , $hupai_uid , $card_number , $mode , $is_tianDI){
        //解析获得本局允许的大胡方式
        $mt_type = explode( "_" , $room_info['room_mtype'] );
        //获取胡牌人的牌面信息
        $hupai_cardInfo = array();
        foreach ( $card_info as $key => $value ){
            if( $value['uid'] == $hupai_uid ){$hupai_cardInfo = $value;}
        }
        //将手牌跟下牌重新进行组合 + 胡的牌；
        $cards  = array();
        //把胡的牌加入到组合中:2018.01.21.BUG:如果当前为自摸且胡的牌为提牌或者畏牌的时候，那么这个牌是不能加入进去的
        $is_add = true;
        if( $mode == 2 ){
            if( strstr( $hupai_cardInfo['card_wei'] , $card_number ) != false ){
                $is_add = false;
            }
            if( strstr( $hupai_cardInfo['card_ti'] , $card_number ) != false ){
                $is_add = false;
            }
        }
        if( $is_add == true ) {
            array_push($cards, $card_number);
        }
        //把手牌跟下牌加入到组合中
        $sp    = explode(",", $hupai_cardInfo['sp'] );
        foreach ( $sp as $key => $value ){
            array_push( $cards , $value );
        }
        $xp    = explode(",", $hupai_cardInfo['xp'] );
        foreach ( $xp as $key => $value ){
            $xp_temp = explode("_",$value);
            foreach ( $xp_temp as $key_1 => $value_1 ){
                array_push( $cards , $value_1 );
            }
        }
        //2018.03.07：BUG：跑胡的情况下会出现该牌多一个的情况
        $count_values = array_count_values( $cards );
        foreach ( $count_values as $key => $value ){
            if( $value == 5 ){
                foreach ( $cards as $key_1 => $value_1 ){
                    if( $key == $value_1 ){
                        unset( $cards[ $key_1 ] );break;//如果出现5个字的情况下，则删除1个即可退出
                    }
                }
            }
        }
        //清除非牌号的排
        foreach ( $cards as $key => $value ){
            if( (int)$value >= 1 && (int)$value <= 20 ){

            }else{
                unset( $cards[$key] );
            }
        }
        //遍历所有牌；记录各种牌的数量
        $hong_Counnt  = 0;//红字数量
        $hei_Count    = 0;//黑字数量
        $dazi_Count   = 0;//大字数量
        $xiaozi_Count = 0;//小字数量
        foreach ( $cards as $key => $value ){
            if( $value == 2 || $value == 7 || $value == 10 || $value == 12 || $value == 17 || $value == 20 ){$hong_Counnt++;}else{$hei_Count++;}//是否为2.7.10
            if( $value <= 10 ){$xiaozi_Count++;}else{$dazi_Count++;}//是否为大小字
        }
        $mode_type = "";
        $plus      = 0;
        //红黑一点红  只可能同时出现一种
        if( in_array( "3" , $mt_type ) ){//是否打红黑胡
            if( $hong_Counnt >= SOR_DAHONG ){//大红 ,是否满足10个以上的红字
                $mode_type = "1";$plus = SOR_1_PLUS;
            }else if( $hong_Counnt >= SOR_XIAOHONG ){//小红,是否满足8个以上的红字
                $mode_type = "2";$plus = SOR_2_PLUS;
            }else if( $hong_Counnt == 0 ){//黑胡,一个都没有
                $mode_type = "4";$plus = SOR_4_PLUS;
            }
        }
        if( in_array( "5" , $mt_type ) ) {//是否打一点红
            if( $hong_Counnt == 1 ){$mode_type = "3";$plus = SOR_3_PLUS;}//一点红
        }
        //如果存在大小字的情况下；继续叠加翻倍
        if( in_array( "4" , $mt_type ) ) {
            if( $xiaozi_Count == 0 ){
                $mode_type = $mode_type . "_5";
                $plus = $plus == 0 ? SOR_5_PLUS : $plus * SOR_5_PLUS;//大字胡
            }
            if( $dazi_Count == 0 ){
                $mode_type = $mode_type . "_6";
                $plus = $plus == 0 ? SOR_6_PLUS : $plus * SOR_6_PLUS;//小字胡
            }
        }
        //如果存在天地胡的情况下，继续叠加翻倍
        if( in_array( "4" , $mt_type ) ) {
            if( $is_tianDI == 1 ){
                $mode_type = $mode_type . "_7";$plus = $plus == 0 ? SOR_7_PLUS : $plus * SOR_7_PLUS;//天胡
            }
            if( $is_tianDI == 2 ){
                $mode_type = $mode_type . "_8";$plus = $plus == 0 ? SOR_8_PLUS : $plus * SOR_8_PLUS;//地胡
            }
        }
        //如果打碰碰胡？继续叠加翻倍
        if( in_array( "6" , $mt_type ) ) {
            if( PHZ_Card::__Cards_ispengHU( $cards ) == true ){
                $mode_type = $mode_type . "_9";$plus = $plus == 0 ? SOR_9_PLUS : $plus * SOR_9_PLUS;//碰碰胡
            }
        }
        //是否自摸，自摸在翻倍 * 2
        if( $mode == 2 ){
            $plus = $plus == 0 ? SOR_ZIMO : $plus * SOR_ZIMO;
        }
        //返回数据
        return array( 'mode_type' => $mode_type , 'plus' => $plus , 'hupai_cardInfo' => $hupai_cardInfo );
    }

    /**
     * 算分操作(这里需要根据房间当前设置的底分进行计算，也需要根据是否放炮来决定各家的分数) ;最后用分数 * 番型
     * @param $room_info
     * @param $huxi
     * @param $hupai_uid
     * @param $pao_uid
     * @param $mt_plus     番型数据(根据里面的PLUS进行算分)
     * @param $hupai_userCardInfo 胡牌人的牌面信息
     * @param $card_number 牌号
     * @param $db_connect 数据标识
     */
    public static function __Calculation_score( $room_info , $huxi , $hupai_uid , $pao_uid , $mt_plus , $hupai_userCardInfo , $card_number , $db_connect ){
        //进行翻醒或者随醒的数据判定
        $mt_type  = explode( "_" , $room_info['room_mtype'] );
        $xingHuXi = false;
        if( in_array( "7" , $mt_type ) ) {
            $xingHuXi = PHZ_Xing::__Xing_Calculation( $room_info['room_id'] , $hupai_userCardInfo , $card_number , "fan" , $db_connect );
        }
        if( in_array( "8" , $mt_type ) ) {
            $xingHuXi = PHZ_Xing::__Xing_Calculation( $room_info['room_id'] , $hupai_userCardInfo , $card_number , "sui" , $db_connect );
        }
        //胡息 + 醒息
        if( $xingHuXi['huxi'] >= 1 ) {
            $huxi = $huxi + $xingHuXi['huxi'];
        }
        //通过番数进行当前的分数判定
        if( $mt_plus['plus'] != 0 ){
            $all_score   = $huxi * $mt_plus['plus'];
        }else{
            $all_score   = $huxi * 1;
        }
        //番后的胡息需要进行判断；3分为基础；1-2分不算分
        if( $all_score % 3 == 1 ){$all_score = $all_score - 1;}
        if( $all_score % 3 == 2 ){$all_score = $all_score - 2;}
        //通过底分计算最后确定分值 - 底分规则暂时还未搞懂；暂不做处理***********先按胡息判定
        //.................
        //初始化数组
        $user_array  = array('player_1' => 0 , 'player_2' => 0 ,'player_3' => 0 , 'player_4' => 0 );
        //如果为放炮，则一人独出，否则为3人平分
        $hupai_index = PHZ_User::__get_user_Room_Index( $room_info , $hupai_uid );
        if( $pao_uid != 0 ){
            $user_array['player_' . $hupai_index ] = $all_score;//胡牌人+
            $pao_index = PHZ_User::__get_user_Room_Index( $room_info , $pao_uid );
            $user_array['player_' . $pao_index ]   = -$all_score;//放炮人-
        }else{
            foreach ( $user_array as $key => $value ){
                if( $key == 'player_' . $hupai_index ){
                    $user_array['player_' . $hupai_index ] = $all_score;//胡牌人+
                }else{
                    $user_array[$key] = -( $all_score / 3 );//其他二家平分 - 3人局，还是3人平分分数，但要少进1个人的钱
                }
            }
        }
        //将醒信息带上返回
        $user_array['xing'] = $xingHuXi;
        return $user_array;
    }

}